const { userIsExistByUsername } = require('../model/userModel')
const { createFail } = require('../utils/result')

const userIsExist = (req, res, next) => {
  const { username } = req.body
  userIsExistByUsername(username)
    .then((results) => {
      if (results.length > 0) {
        res.json(createFail('用户名已存在'))
      } else {
        next()
      }
    })
    .catch(() => {
      res.json(createFail('服务端异常'))
    })
}

// 校验用户是否登录
const isLogin = (req, res, next) => {
  const { user } = req.session
  if (user && user.id) {
    next()
  } else {
    res.json(createFail('请先登录'))
  }
}

module.exports = { userIsExist, isLogin }
